/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package auctions;

import java.util.Arrays;
import java.util.ArrayList;

/**
 *
 * @author hangsu
 */
public class ScheduleSealedbidAuction extends ScheduleAuction {
    
    private int paymentRule;

    public ScheduleSealedbidAuction(int auctionIdx, int paymentRule) {
        super(auctionIdx, AuctionType.SEALEDBID);
        this.paymentRule = paymentRule;
    }
    
    public void setPaymentRule(int prule) {
        this.paymentRule = prule;
    }
    
    @Override
    public void runAuction() {
        
        //this.clear();
        double maxBid = 0;
        int maxBidder = -1;
        int agentIdx;
        Double[] bids = new Double[this.bidderNum];
        for(agentIdx=0; agentIdx<this.bidderNum;agentIdx++) {
            bids[agentIdx]=this.agents.get(agentIdx).getBid();
            if(bids[agentIdx] > maxBid) {
                maxBid = bids[agentIdx];
                maxBidder = agentIdx;
            }
        }

        ArrayList<Double> newBids = new ArrayList(Arrays.asList(bids));
        this.result.setBidsNewRound(newBids);
        
        this.quiet = true;
        
        /* no valid bid */
        if(maxBid<this.reservePrice) {
            this.result.setFinalResult(new AuctionStatus(this.auctionIdx,-1, maxBid, this.reservePrice));
            /*
             * this is moved to auction house
             *
            for (ScheduleAgent a : this.agents)
                a.reportResult(this.result);
            */
            return;
        }
        
        Arrays.sort(bids);
        
        //Now determine the winning price
        double price;
        int priceIdx = this.bidderNum - this.paymentRule;
        if(priceIdx<0) {
            price = this.reservePrice;
        } else {
            price = bids[priceIdx];
            if(price<this.reservePrice)
                price = this.reservePrice;
        }
        
        this.result.setFinalResult(new AuctionStatus(this.auctionIdx,maxBidder, maxBid, price));
        /*
         * this is moved to auction house
        for (ScheduleAgent a : this.agents)
            a.reportResult(this.result);
        */
        return ;
        
    }

    @Override
    public void initializeBidders() {
        /* pass initial info about auction to bidders, if necessary */
    }
    
}
